package com.shopping;

import java.io.IOException;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.shopping.model.ShoppingCategory;
import com.liferay.portlet.shopping.model.ShoppingItem;
import com.liferay.portlet.shopping.service.ShoppingCategoryLocalServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingItemLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.util.CartUtil;

/**
 * Portlet implementation class ShoppingPortlet
 */
public class ShoppingPortlet extends MVCPortlet {
	
	@Override
	public void init() throws PortletException {
		// TODO Auto-generated method stub
		
		super.init();
		addProcessActionSuccessMessage = false;
	}

	@Override
	public void render(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		long itemId = ParamUtil.getLong(request, "itemId", 0l);

		ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
		long groupId = themeDisplay.getScopeGroupId();

		if (itemId <= 0l) {
			long parentCategoryId = ParamUtil.getLong(request, "parentCategoryId");

			List<ShoppingCategory> categories = null;
			try {
				categories = ShoppingCategoryLocalServiceUtil.getCategories(groupId, parentCategoryId, 0, -1);
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (categories != null && categories.size() > 0) {
				request.setAttribute("CATEGORIES", categories);
			}

			List<ShoppingItem> items = null;
			try {
				items = ShoppingItemLocalServiceUtil
						.getItems(groupId, parentCategoryId);
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (items != null && items.size() > 0) {
				request.setAttribute("ITEMS", items);
			}

			viewTemplate = "/html/donate-now/view.jsp";

		} else {

			request.setAttribute("ITEM_ID", String.valueOf(itemId));
			viewTemplate = "/html/donate-now/item-details.jsp";
		}

		super.render(request, response);
	}
	
	public void addToCart(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {

		CartUtil.addToCart(actionRequest);
	}
}